import Vue from "vue";
import VueRouter from "vue-router";
import router_modular from "@/router/router_modular/index.js";
Vue.use(VueRouter);

const routes = [...router_modular];
const WHITE_LIST = ["/login", "/register", "/aboutMine", "/policy"];
const router = new VueRouter({
  mode: "history",
  routes,
  scrollBehavior() {
    return { x: 0, y: 0, behavior: "instant" }; // 所有页面切换强制置顶
  },
});
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem("token");

  // 如果路由需要认证且未登录，重定向到登录页
  if (
    to.matched.some((record) => record.meta.requiresAuth !== false) &&
    !isAuthenticated
  ) {
    if (to.meta.specialBar) {
      if (to.path === "/card-bind" && to.query.cardNo && to.query.cardPwd) {
        localStorage.setItem("cardNo", to.query.cardNo); // 存储卡号
        localStorage.setItem("cardPwd", to.query.cardPwd); // 存储卡密
      }

      next("/register");
    } else {
      if (!WHITE_LIST.includes(router.currentRoute.path)) {
        next("/login");
      } else {
        next();
      }
    }
  } else {
    if (to.meta.title) {
      document.title = to.meta.title;
    } else {
      document.title = "职工观影平台";
    }
    next();
  }
});
router.afterEach((to, from) => {});
export default router;
